package com.aiatomic.couting;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.aiatomic.couting.account.CurrencyChangeEventDispatcher;
import com.aiatomic.couting.account.CurrencyChangeEventListener;
import com.aiatomic.couting.account.FragmentAccountInfoFeedback;
import com.aiatomic.couting.account.FragmentAccountInfoMain;
import com.aiatomic.couting.account.FragmentAccountInfoOrders;
import com.aiatomic.couting.account.FragmentAccountInfoShop;
import com.aiatomic.couting.models.OrderEntity;
import com.aiatomic.couting.util.AppUtils;
import com.aiatomic.couting.util.HttpUtils;
import com.aiatomic.couting.util.SystemUtil;
import com.aiatomic.couting.widgets.LoadingDialog;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class AccountInfoActivity extends Activity implements CurrencyChangeEventListener {
	public static final String ACTION_MAIN = "fragment_account_info_main";
	public static final String ACTION_FEEDBACK = "fragment_account_info_feedback";
	public static final String ACTION_SHOP = "fragment_account_info_shop";
	public static final String ACTION_ORDERS = "fragment_account_info_orders";
	private LoadingDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_account_info);
		TextView txtBack = (TextView) this.findViewById(R.id.txtBack);
		txtBack.setText(R.string.back);
		txtBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		TextView txtNext = (TextView) this.findViewById(R.id.txtNext);
		txtNext.setVisibility(View.INVISIBLE);

		TextView txtMiddle = (TextView) this.findViewById(R.id.txtMiddle);
		txtMiddle.setVisibility(View.VISIBLE);
		txtMiddle.setText(R.string.account_info_title);
		dialog = new LoadingDialog(this);
		CurrencyChangeEventDispatcher.getInstance().registListener(this);
		((TextView) this.findViewById(R.id.txt_currency_days)).setText(String.valueOf(AppUtils.currency_day));
		Fragment fragment = null;
		String action = getIntent().getAction();
		if (action == null) {
			action = ACTION_MAIN;
		}
		switch (action) {
		case ACTION_MAIN:
			fragment = new FragmentAccountInfoMain();
			break;
		case ACTION_FEEDBACK:
			fragment = new FragmentAccountInfoFeedback();
			break;
		case ACTION_ORDERS:
			fragment = new FragmentAccountInfoOrders();
			break;
		case ACTION_SHOP:
			fragment = new FragmentAccountInfoShop();
			break;
		}
		addFragment(fragment);
	}

	public void addFragment(Fragment fragment) {
		FragmentManager fm = getFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();
		transaction.replace(R.id.account_content, fragment);
		transaction.addToBackStack(null);
		transaction.commit();
	}

	@Override

	public void onBackPressed() {

		FragmentManager fm = getFragmentManager();

		if (fm.getBackStackEntryCount() > 1) {

			fm.popBackStackImmediate();

		} else {
			this.finish();
		}

	}

	public void addOrder(String gid) {
		dialog.setMessage(getString(R.string.addOrder));
		dialog.show();
		Map<String, String> params = new HashMap<String, String>();
		params.put("platform", String.valueOf(IConstant.PLATFORM));
		params.put("aid", AppUtils.aid);
		params.put("gid", gid);
		params.put("client_version", SystemUtil.getAppVersion(AccountInfoActivity.this));
		params.put("time", String.valueOf(Calendar.getInstance().getTimeInMillis()));
		params.put("channel", String.valueOf(AppUtils.channel));
		params.put("sign",
				HttpUtils.md5(params.get("aid") + params.get("gid") + params.get("time") + params.get("client_version")
						+ params.get("platform") + params.get("channel") + IConstant.NORMAL_MD5_KEY));
		params.put("ssign", HttpUtils.md5(params.get("aid") + params.get("gid") + params.get("time")
				+ params.get("client_version") + params.get("platform") + params.get("channel") + AppUtils.sKey));
		HttpUtils.post(new Handler() {

			@Override
			public void handleMessage(Message msg) {
				dialog.cancel();
				if (msg.what == HttpUtils.CODE_SUCCESS_RQ_100) {
					try {
						JSONObject json = new JSONObject(msg.obj.toString());
						if (json.getInt("code") == HttpUtils.RET_SUCCESS) {
							OrderEntity entity = new OrderEntity();
							entity.setGood_id(json.getString("product_id"));
							entity.setDiscout(json.getDouble("discount"));
							entity.setGm_user_id(json.getString("gm_account_id"));
							entity.setGm_user_name(json.getString("gm_user_name"));
							entity.setPrice(json.getDouble("price"));
							entity.setGm_order_id(json.getString("gm_order_id"));
							Calendar ctime=Calendar.getInstance();
							ctime.setTimeInMillis(json.getLong("create_time")*1000);
							entity.setCreated_time_loc(ctime.getTime());
							entity.setReal_give_days(json.getInt("real_give"));
							Calendar utime=Calendar.getInstance();
							utime.setTimeInMillis(json.getLong("update_time")*1000);
							entity.setPayed_time_loc(utime.getTime());
							entity.setReal_money(json.getDouble("real_price"));
							entity.setGood_desc(json.getString("desc"));
							
							Intent intent = new Intent(AccountInfoActivity.this, PayActivity.class);
							intent.putExtra("oid", json.getString("gm_order_id"));
							intent.putExtra("real_price", json.getString("real_price"));
							intent.putExtra("name", json.getString("name"));
							intent.putExtra("desc", json.getString("desc"));
							intent.putExtra("order", entity);
							AccountInfoActivity.this.startActivity(intent);
						} else {
							Toast toast = Toast.makeText(AccountInfoActivity.this, json.getString("msg"),
									Toast.LENGTH_LONG);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.e("", msg.obj.toString());
						Toast toast = Toast.makeText(AccountInfoActivity.this,
								AccountInfoActivity.this.getResources().getString(R.string.server_format_error),
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
				} else {
					Toast toast = Toast.makeText(AccountInfoActivity.this, ICodeMsg.ERROR_CODES_HTTP.get(msg.what),
							Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}
			}

		}, AppUtils.url + "/v/cRecharge/addOrder/", params);
	}

	@Override
	public void onCurrencyChangeEvent(int eventCode) {
		((TextView) this.findViewById(R.id.txt_currency_days)).setText(String.valueOf(AppUtils.currency_day));
	}

}
